'use strict '

let fs=require('fs');
let path=require('path')
let router=require('koa-router')();

function selFiles(dir){
    let files=fs.readdirSync(dir)
    return files.filter(name=>{
        return name.endsWith('.js') && name!=='index.js'
    })

}

function registRouter(fiels){

    fiels.forEach(item => {
        let currentPath=path.join(__dirname,item)

        let routerObj=require(currentPath);

        for(let key in routerObj){
            let type=routerObj[key][0];
            let fn=routerObj[key][1];

            if(type==="get"){
                router.get(key,fn)
            }else if(type==='post'){
                router.post(key,fn)
            }else{
                console.log('类型错误');
            }
        }

    });
}


module.exports=function(dir){
    let fullPath= dir || __dirname;

    let a=selFiles(fullPath);
    registRouter(a)

    return router.routes();
}